package com.zeng.jiudian.servlet.user;

import com.alibaba.fastjson.JSONObject;
import com.zeng.jiudian.bean.UserModel;
import com.zeng.jiudian.service.UserService;
import com.zeng.jiudian.service.impl.UserServiceImpl;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author JJ_yo
 * @Date 2020/7/20-14:06
 */
@WebServlet("/login")
public class UserLoginServlet extends HttpServlet
{
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        Object sessionCode = req.getSession().getAttribute("code");

        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");

        UserModel userModel = new UserModel();
        userModel.setUsername(username);
        userModel.setPassword(password);
        userModel.setCode(code);
        userModel.setSessionCode((String) sessionCode);

        UserService userService = new UserServiceImpl();
        int result = userService.login(userModel);

        if (result == 1)
        {
            //req.getSession().setAttribute("username", username);
            Jedis jedis = new Jedis();
            jedis.select(1);
            jedis.setex(username, 86400, username);
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", result);
        resp.getWriter().println(jsonObject);
    }
}
